import { Message } from 'element-ui'
import { del } from './requestCommon'

export function showData(response, vm) {
  if (response.code === 200) {
    const data = response.data
    vm.tableData = data.records
    vm.pageNum = data.current
    vm.total = data.total
    vm.loading = false
  } else {
    Message({
      message: response.msg,
      type: 'error',
      duration: 5 * 1000
    })
  }
}

export function success(msg) {
  Message.success(msg)
}

export function fail(msg) {
  Message({
    message: msg,
    type: 'error',
    duration: 3 * 1000
  })
}

export function deleteData(rows) {
  if (rows.length === 0) {
    Message({
      message: '请选择要删除的数据',
      type: 'error',
      duration: 3 * 1000
    })
    return false
  }
  return true
}

export function validate(vm, formName) {
  let fast = true
  vm.$refs[formName].validate((valid) => {
    if (!valid) {
      fast = false
    }
  })
  return fast
}

/**
 * File转base64
 * @param file
 * @return base64
 * */
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let fileResult = ''
    reader.readAsDataURL(file)
    // 开始转
    reader.onload = () => {
      fileResult = reader.result
    }
    // 转失败
    reader.onerror = (error) => {
      reject(error)
    }
    // 结束 resolve
    reader.onloadend = () => {
      resolve(fileResult)
    }
  })
}

export function resetForm(vm, formName) {
  vm.$refs[formName].resetFields()
}

export function showAttribute(response, vm, attribute) {
  if (response.code === 200) {
    vm[attribute] = response.data
  } else {
    fail(response.msg)
  }
}

export function delData(action, id, vm) {
  debugger
  vm.$confirm('此操作将永久删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    del(action, id).then(res => {
      if (res.code === 200) {
        success(res.msg)
        vm.loadData()
      } else {
        fail(res.msg)
      }
    })
  }).catch(() => {

  })
}

export function fileToBase64(file) {
  return new Promise(function(resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function() {
      imgResult = reader.result
    }
    reader.onerror = function(error) {
      reject(error)
    }
    reader.onloadend = function() {
      resolve(imgResult)
    }
  })
}
